import React, { Component } from 'react'
import { Tabs } from 'antd'
import qs from 'qs'

import { checkPermission } from '@/components/AuthComponent/utils'
import AuthComponent from '@/components/AuthComponent'

import IpConfig from './Tabs/IpConfig'
import LogConfig from './Tabs/LogConfig'

import './index.less'

@AuthComponent('setting')
export default class SettingHome extends Component {
  constructor(props) {
    super(props)
    const { location: { search }} = props
    const query = qs.parse((search || '').slice(1))
    const tabsList = [
      {
        key: '1',
        label: <span>ip黑名单配置</span>,
        comp: (props) => <IpConfig {...props} />,
        authKey: 'setting-ipconfig',
      },
      {
        key: '2',
        label: '日志空间容量预警',
        comp: (props) => <LogConfig {...props} />,
        authKey: 'setting-logconfig',
      },
    ].filter(v => checkPermission(v.authKey))

    this.state = {
      activeKey: query.activeKey || (tabsList[0] || {}).key || '1',
      tabsList,
    }
  }

  changeFn = (activeKey) => {
    this.setState({
      activeKey,
    })
    const { location: { pathname }} = this.props
    this.props.history.replace({
      pathname,
      search: `?activeKey=${activeKey}`,
    })
  }

  render() {
    const { activeKey, tabsList } = this.state
    return <div className="SettingHome">
      <Tabs destroyInactiveTabPane activeKey={activeKey} onChange={this.changeFn}>
        {
          tabsList.map(element => {
            const Component = element.comp
            return (
              <TabPane tab={element.label} key={element.key}>
                {
                  activeKey === element.key &&
                        <Component {...this.props} />
                }
              </TabPane>
            )
          })
        }
      </Tabs>
    </div>
  }
}

const { TabPane } = Tabs

